<!--
  广播消息调试工具
  
  专门用于调试广播消息在主窗口和子窗口之间的传输问题
-->

<template>
  <div class="broadcast-debug">
    <div class="header">
      <h2>🔍 广播消息调试工具</h2>
      <p class="subtitle">检测和调试多窗口广播通信问题</p>
    </div>

    <!-- API 可用性检测 -->
    <div class="section">
      <h3>📋 API 可用性检测</h3>
      <div class="detection-grid">
        <div class="detection-item">
          <span class="label">window.api:</span>
          <span :class="['status', apiAvailable ? 'success' : 'error']">
            {{ apiAvailable ? '✅ 可用' : '❌ 不可用' }}
          </span>
        </div>
        <div class="detection-item">
          <span class="label">window.api.broadcast:</span>
          <span :class="['status', broadcastAvailable ? 'success' : 'error']">
            {{ broadcastAvailable ? '✅ 可用' : '❌ 不可用' }}
          </span>
        </div>
        <div class="detection-item">
          <span class="label">broadcast.send:</span>
          <span :class="['status', broadcastSendAvailable ? 'success' : 'error']">
            {{ broadcastSendAvailable ? '✅ 可用' : '❌ 不可用' }}
          </span>
        </div>
        <div class="detection-item">
          <span class="label">broadcast.on:</span>
          <span :class="['status', broadcastOnAvailable ? 'success' : 'error']">
            {{ broadcastOnAvailable ? '✅ 可用' : '❌ 不可用' }}
          </span>
        </div>
      </div>
    </div>

    <!-- 广播消息测试 -->
    <div class="section">
      <h3>📡 广播消息测试</h3>
      <div class="test-controls">
        <div class="form-group">
          <label>测试频道:</label>
          <input v-model="testChannel" class="input" placeholder="输入频道名称" />
        </div>
        <div class="form-group">
          <label>测试消息:</label>
          <input v-model="testMessage" class="input" placeholder="输入测试消息" />
        </div>
        <div class="form-group">
          <label>窗口类型标识:</label>
          <span class="window-type">{{ windowType }}</span>
        </div>
        <button @click="sendTestMessage" class="btn btn-primary">发送测试消息</button>
        <button @click="setupListener" class="btn btn-success">设置监听器</button>
        <button @click="clearLogs" class="btn btn-warning">清空日志</button>
      </div>
    </div>

    <!-- 消息日志 -->
    <div class="section">
      <h3>📝 消息日志</h3>
      <div class="log-container">
        <div v-if="messageLogs.length === 0" class="empty-log">
          还没有任何消息日志
        </div>
        <div v-for="(log, index) in messageLogs" :key="index" class="log-item">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-type">{{ log.type }}</span>
          <span class="log-channel">{{ log.channel }}</span>
          <span class="log-content">{{ log.content }}</span>
        </div>
      </div>
    </div>

    <!-- 详细信息 -->
    <div class="section">
      <h3>ℹ️ 详细信息</h3>
      <div class="info-grid">
        <div class="info-item">
          <label>当前URL:</label>
          <span>{{ currentUrl }}</span>
        </div>
        <div class="info-item">
          <label>URL参数:</label>
          <span>{{ urlParams }}</span>
        </div>
        <div class="info-item">
          <label>页面加载时间:</label>
          <span>{{ loadTime }}</span>
        </div>
        <div class="info-item">
          <label>监听器数量:</label>
          <span>{{ listenerCount }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const testChannel = ref('debug-test')
const testMessage = ref('Hello from debug tool!')
const messageLogs = ref<Array<{
  time: string
  type: string
  channel: string
  content: string
}>>([])
const listenerCount = ref(0)
const loadTime = ref('')
const currentUrl = ref('')
const urlParams = ref('')

// API 可用性检测
const apiAvailable = computed(() => {
  return typeof window !== 'undefined' && 'api' in window && window.api != null
})

const broadcastAvailable = computed(() => {
  return apiAvailable.value && 'broadcast' in window.api && window.api.broadcast != null
})

const broadcastSendAvailable = computed(() => {
  return broadcastAvailable.value && typeof window.api.broadcast.send === 'function'
})

const broadcastOnAvailable = computed(() => {
  return broadcastAvailable.value && typeof window.api.broadcast.on === 'function'
})

// 窗口类型检测
const windowType = computed(() => {
  if (typeof window === 'undefined') return 'Unknown'
  
  const url = new URL(window.location.href)
  const type = url.searchParams.get('type')
  const hash = window.location.hash
  
  if (type === 'child-window' || hash.includes('child-window')) {
    return '子窗口 (Child Window)'
  }
  return '主窗口 (Main Window)'
})

/**
 * 添加日志
 */
const addLog = (type: string, channel: string, content: string) => {
  messageLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    type,
    channel,
    content
  })
  
  // 只保留最近20条日志
  if (messageLogs.value.length > 20) {
    messageLogs.value.pop()
  }
}

/**
 * 发送测试消息
 */
const sendTestMessage = () => {
  if (!testChannel.value.trim() || !testMessage.value.trim()) {
    alert('请输入频道名称和消息内容')
    return
  }
  
  if (!broadcastSendAvailable.value) {
    alert('广播发送功能不可用')
    return
  }
  
  try {
    const messageData = {
      content: testMessage.value,
      sender: windowType.value,
      timestamp: new Date().toISOString(),
      debug: true
    }
    
    console.log(`[调试工具] 发送消息到频道: ${testChannel.value}`, messageData)
    window.api.broadcast.send(testChannel.value, messageData)
    
    addLog('发送', testChannel.value, testMessage.value)
  } catch (error) {
    console.error('[调试工具] 发送消息失败:', error)
    addLog('错误', testChannel.value, `发送失败: ${error}`)
  }
}

/**
 * 设置监听器
 */
const setupListener = () => {
  if (!testChannel.value.trim()) {
    alert('请输入频道名称')
    return
  }
  
  if (!broadcastOnAvailable.value) {
    alert('广播监听功能不可用')
    return
  }
  
  try {
    console.log(`[调试工具] 设置监听器: ${testChannel.value}`)
    
    window.api.broadcast.on(testChannel.value, (data) => {
      console.log(`[调试工具] 收到消息:`, data)
      addLog('接收', testChannel.value, data.content || JSON.stringify(data))
    })
    
    listenerCount.value++
    addLog('系统', testChannel.value, '监听器已设置')
  } catch (error) {
    console.error('[调试工具] 设置监听器失败:', error)
    addLog('错误', testChannel.value, `监听器设置失败: ${error}`)
  }
}

/**
 * 清空日志
 */
const clearLogs = () => {
  messageLogs.value = []
  addLog('系统', '', '日志已清空')
}

// 生命周期
onMounted(() => {
  loadTime.value = new Date().toLocaleTimeString()
  currentUrl.value = window.location.href
  
  // 解析URL参数
  const params = new URLSearchParams(window.location.search)
  const paramsObj: Record<string, string> = {}
  params.forEach((value, key) => {
    paramsObj[key] = value
  })
  urlParams.value = JSON.stringify(paramsObj)
  
  console.log('[调试工具] 页面加载完成')
  console.log('[调试工具] 窗口类型:', windowType.value)
  console.log('[调试工具] API可用性:', {
    api: apiAvailable.value,
    broadcast: broadcastAvailable.value,
    send: broadcastSendAvailable.value,
    on: broadcastOnAvailable.value
  })
  
  addLog('系统', '', '调试工具已加载')
})
</script>

<style scoped>
.broadcast-debug {
  min-height: 100vh;
  box-sizing: border-box;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #333;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  color: white;
}

.header h2 {
  margin: 0 0 10px 0;
  font-size: 2em;
}

.subtitle {
  margin: 0;
  opacity: 0.9;
  font-size: 1.1em;
}

.section {
  background: white;
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.section h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 1.3em;
}

/* API检测 */
.detection-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.detection-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #e9ecef;
}

.label {
  font-weight: 600;
  color: #495057;
}

.status.success {
  color: #28a745;
  font-weight: 600;
}

.status.error {
  color: #dc3545;
  font-weight: 600;
}

/* 测试控制 */
.test-controls {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 600;
  color: #495057;
  font-size: 14px;
}

.input {
  padding: 10px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.window-type {
  padding: 8px 12px;
  background: #e3f2fd;
  color: #1976d2;
  border-radius: 6px;
  font-weight: 600;
  font-size: 14px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
  transform: translateY(-2px);
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-success:hover {
  background: #1e7e34;
  transform: translateY(-2px);
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-warning:hover {
  background: #e0a800;
  transform: translateY(-2px);
}

/* 日志显示 */
.log-container {
  max-height: 300px;
  overflow-y: auto;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  background: #f8f9fa;
}

.empty-log {
  padding: 30px;
  text-align: center;
  color: #6c757d;
  font-style: italic;
}

.log-item {
  display: grid;
  grid-template-columns: 80px 60px 100px 1fr;
  gap: 10px;
  padding: 10px 15px;
  border-bottom: 1px solid #e9ecef;
  font-size: 13px;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  color: #6c757d;
  font-family: monospace;
}

.log-type {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 600;
  text-align: center;
}

.log-item:nth-child(odd) .log-type {
  background: #e3f2fd;
  color: #1976d2;
}

.log-item:nth-child(even) .log-type {
  background: #f3e5f5;
  color: #7b1fa2;
}

.log-channel {
  color: #495057;
  font-weight: 600;
  font-family: monospace;
}

.log-content {
  color: #212529;
}

/* 详细信息 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #17a2b8;
}

.info-item label {
  font-weight: 600;
  color: #495057;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.info-item span {
  font-family: monospace;
  font-size: 13px;
  color: #212529;
  word-break: break-all;
}
</style>

